import React, { useEffect, useImperativeHandle, useState } from 'react'
import { Form, Input, Modal, Select, TreeSelect, Upload, message } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { IModalProps, ModelAction } from '@/types/modal'
import { getItem } from '@/utils/storage'
import type { UploadChangeParam } from 'antd/es/upload'
import { getDeptList } from '@/api/dept'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { IUserItem } from '@/types/user'
import { createUser, editUser } from '@/api/user'
import { IDeptItem } from '@/types/dept'
import { IRoleItem } from '@/types/roles'
import { getAllRoleList } from '@/api/roles'

const CreateUser: React.FC<IModalProps<IUserItem>> = props => {
  const [action, setAction] = useState<ModelAction>('create')
  const [visiable, setVisiable] = useState(false)
  const [imageUrl, setImageUrl] = useState('')
  const [loading, setLoading] = useState(false)
  const [deptList, setDeptList] = useState<IDeptItem[]>([])
  const [roleList, setRoleList] = useState<IRoleItem[]>([])
  const [form] = Form.useForm()

  // 自定义mRef,将open方法暴露给父组件使用
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })

  useEffect(() => {
    getAllDeptList()
    getRoleList()
  }, [])

  // 获取部门列表
  const getAllDeptList = async () => {
    const { data } = await getDeptList()
    setDeptList(data)
  }

  // 获取角色列表
  const getRoleList = async () => {
    const { data } = await getAllRoleList()
    setRoleList(data)
  }

  // 显示
  const open = (type: ModelAction, data?: IUserItem) => {
    console.log('open:', type, data)

    if (type === 'edit' && data) {
      form.setFieldsValue(data)
      setImageUrl(data.userImg)
    }
    setAction(type)
    setVisiable(true)
  }

  // 提交
  const handleSubmit = () => {
    form.validateFields().then(vaild => {
      if (vaild) {
        const params = {
          ...form.getFieldsValue(),
          userImg: imageUrl
        }
        console.log(params)
        if (action === 'create') {
          createUser(params).then(() => {
            message.success('创建成功')
            props.update()
          })
        } else {
          editUser(params).then(() => {
            message.success('修改成功')
            props.update()
          })
        }
        onCancel()
      }
    })
  }

  // 关闭
  const onCancel = () => {
    setVisiable(false)
    setImageUrl('')
    form.resetFields()
  }

  // 头像上传
  const beforeUpload = (file: RcFile) => {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isImage) {
      message.error('只能上传png或jpg格式的图片')
      return false
    }
    const isLt500K = file.size / 1024 / 1024 < 0.5
    if (!isLt500K) {
      message.error('图片不能超过500k')
      return false
    }
    return true
  }
  // 上传后，图片处理
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      setLoading(false)
      const { code, data } = info.file.response
      console.log('...', data)

      if (code === 0) {
        setImageUrl(data.file)
      } else {
        message.error('上传失败')
      }
    } else if (info.file.status === 'error') {
      message.error('服务器异常，请稍后重试')
    }
  }

  return (
    <Modal
      title={action === 'create' ? '创建用户' : '编辑用户'}
      width={800}
      okText='确定'
      cancelText='取消'
      open={visiable}
      onCancel={onCancel}
      onOk={handleSubmit}
    >
      <Form form={form} initialValues={{ state: 1 }}>
        <Form.Item name='userId' hidden>
          <Input />
        </Form.Item>
        <Form.Item label='用户名' name='userName' rules={[{ required: true, message: '请输入用户名' }]}>
          <Input></Input>
        </Form.Item>
        <Form.Item
          label='邮箱'
          name='userEmail'
          rules={[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入正确的邮箱' }
          ]}
        >
          <Input disabled={action === 'edit'}></Input>
        </Form.Item>
        <Form.Item
          label='手机号'
          name='mobile'
          validateTrigger='onBlur'
          rules={[{ pattern: new RegExp(/^[1][3-9][0-9]{9}$/, 'g'), message: '请输入正确的手机号' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item label='部门' name='deptId'>
          <TreeSelect
            placeholder='请选择部门'
            allowClear
            treeDefaultExpandAll
            showCheckedStrategy={TreeSelect.SHOW_ALL}
            fieldNames={{ label: 'deptName', value: '_id' }}
            treeData={deptList}
          />
        </Form.Item>
        <Form.Item label='岗位' name='job'>
          <Input></Input>
        </Form.Item>
        <Form.Item label='状态' name='state'>
          <Select>
            <Select.Option value={1}>在职</Select.Option>
            <Select.Option value={2}>离职</Select.Option>
            <Select.Option value={3}>试用期</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label='系统角色' name='roleList'>
          <Select placeholder='请选择角色'>
            {roleList.map(item => {
              return (
                <Select.Option value={item._id} key={item._id}>
                  {item.roleName}
                </Select.Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item label='用户头像'>
          <Upload
            name='avatar'
            listType='picture-card'
            showUploadList={false}
            headers={{
              Authorization: 'Bearer ' + getItem('token'),
              icode: 'FD1C6FDDB72FEA56'
            }}
            action='/api/users/upload'
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt='avatar' style={{ width: '100%' }} />
            ) : (
              <div>
                {loading ? <LoadingOutlined rev={undefined} /> : <PlusOutlined rev={undefined} />}
                <div style={{ marginTop: 5 }}>上传头像</div>
              </div>
            )}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateUser
